<script lang="ts" setup>
import { useVModel } from '@vueuse/core'
import { reactive, ref, watch } from 'vue'
import Api from '@/api/'
import to from '@/utils/awaitTo'
import { cloneDeep } from 'lodash-es'
import { message } from 'ant-design-vue'

import { useI18n } from '@/hooks/useI18n'

const { t } = useI18n()

// 声明参数
const props = defineProps({
  // 标题
  data: {
    type: Object,
    default: () => {
    }
  },

  // 开关
  open: {
    type: Boolean,
    required: true
  },

  // 绑定列表
  tiktokList: {
    type: Array,
    default: () => []
  },

  // 绑定回显
  tiktokEchoList: {
    type: Array,
    default: () => []
  },

  formData: {
    type: Object,
    default: () => {
    }
  }
})


// 声明方法
const emit = defineEmits(['update:open', 'callback'])

// 双向绑定方法
const openVModel = useVModel(props, 'open', emit)


// 响应式数据
const formRef = ref()

const form = reactive({
  status: undefined,
  secId: undefined,
  yunyingId: undefined,
  channelId: undefined,
  silp2: undefined,
  producerId: undefined,
  ids: []
})
const tiktokData = reactive({
  open: false,
  title: '',
  form: {},
  loading: false,
  producerList: [],
  channelList: [],
  getCommercialAffairs: [],
  getYunying: [],
  hospitalList: [],
  tiktokList: []
})

// 规则
const rules = {
  ids: [
    {
      required: true,
      message: t('routes.user.tiktok.rules.tiktok'),
      trigger: 'change'
    }
  ],
  secId: [
    {
      required: true,
      message: t('routes.user.tiktok.rules.secId'),
      trigger: 'change'
    }
  ],
  yunyingId: [
    {
      required: true,
      message: t('routes.user.tiktok.rules.yunying'),
      trigger: ['change', 'blur']
    }
  ],
  producerId: [
    {
      required: true,
      message: t('routes.user.tiktok.rules.producer'),
      trigger: ['change', 'blur']
    }
  ]
}

// 完成
const handleOk = (formEl) => {
  if (!formEl) return
  formEl.validate().then(async (values) => {
    const type = Number(values.status)
    let params = { userId: props.formData.userId }

    // 新增
    if (type === 520) {
      params = Object.assign({}, params, { code: '' }, values)
      console.log(params)
      const [error, data] = await to(Api.user.userAddTikTok(params))
      if (!error) {
        console.log(data)
        message.success('绑定成功')
        openVModel.value = false
      }
    }
    // 修改
    if (type === 521) {
      params = Object.assign({}, params, values, { ids: values.ids.join() })
      console.log(params)
      const [error, data] = await to(Api.user.userBoundTikTok(params))
      if (!error) {
        console.log(data)
        message.success('绑定成功')
        openVModel.value = false
      }
    }
  })
}


/** 监听开关 */
watch(() => openVModel.value, (Val) => {
  if (Val) {
    tiktokData.tiktokList = props.tiktokList
    if (props.tiktokEchoList && props.tiktokEchoList.length) {
      form.status = String(521)
      form.ids = props.tiktokEchoList // 有没有选中的抖音号列表
    } else {
      form.status = String(520)
    }
  }
})


/**
 * @description 抖音号
 * @param {String} label
 * @param {String} value
 */
const TikTokStatusDict = [
  {
    label: t('routes.user.tiktok.form.addTiktok'),
    value: `520`
  },
  {
    label: t('routes.user.tiktok.form.bindTiktok'),
    value: `521`
  }
]

//回显运营商务制作人
const getEchoBusProd = async () => {
  const [error, data] = await to(Api.user.userEchoTikTok())
  if (!error) {
    // console.log(data);
    const { channel, commercialAffairs, hospital, producer, yunying } = data
    // console.log(channel, commercialAffairs, hospital, producer, yunying)
    tiktokData.getYunying = yunying // 运营
    tiktokData.producerList = producer // 制作人
    tiktokData.channelList = channel // 渠道
    tiktokData.getCommercialAffairs = commercialAffairs // 商务
    tiktokData.hospitalList = hospital // 医院
  }
}

// 多选限制
const handleOnChange = async (values) => {
  const list = cloneDeep(form.ids)
  form.ids = list.filter((item) => item === values)
}

getEchoBusProd()
</script>

<template>
  <a-modal v-model:open="openVModel" :title="$t('routes.user.tiktok.bingTiktok')" @ok="handleOk(formRef)">
    <a-form ref="formRef" :model="form" :rules="rules">
      <a-form-item :label="$t('routes.user.tiktok.chooseType')" name="status">
        <a-radio-group v-model:value="form.status">
          <a-radio-button
            v-for="item in TikTokStatusDict"
            :key="item.value"
            :value="item.value"
          >{{ item.label }}
          </a-radio-button
          >
        </a-radio-group>
      </a-form-item>

      <a-form-item v-if="Number(form.status) === 520" :label="$t('routes.user.tiktok.secId')" name="secId">
        <a-textarea
          v-model:value="form.secId"
          :placeholder="$t('routes.user.tiktok.secIdPlaceholder')"
        />
      </a-form-item>

      <a-form-item v-if="Number(form.status) === 520" :label="$t('routes.user.tiktok.operation')" name="yunyingId">
        <a-select
          v-model:value="form.yunyingId"
          :fieldNames="{ label: 'name', value: 'id' }"
          :not-found-content="tiktokData.loading ? undefined : null"
          :options="tiktokData.getYunying"
          :placeholder="$t('routes.user.tiktok.operationPlaceholder')"
        >
          <template v-if="tiktokData.loading" #notFoundContent>
            <a-spin size="small" />
          </template>
        </a-select>
      </a-form-item>

      <a-form-item v-if="Number(form.status) === 520" :label="$t('routes.user.tiktok.business')" name="channelId">
        <a-select
          v-model:value="form.channelId"
          :fieldNames="{ label: 'name', value: 'id' }"
          :not-found-content="tiktokData.loading ? undefined : null"
          :options="tiktokData.getCommercialAffairs"
          :placeholder="$t('routes.user.tiktok.businessPlaceholder')"
        >
          <template v-if="tiktokData.loading" #notFoundContent>
            <a-spin size="small" />
          </template>
        </a-select>
      </a-form-item>

      <a-form-item v-if="Number(form.status) === 520" :label="$t('routes.user.tiktok.channel')" name="silp2">
        <a-select
          v-model:value="form.silp2"
          :fieldNames="{ label: 'name', value: 'id' }"
          :not-found-content="tiktokData.loading ? undefined : null"
          :options="tiktokData.channelList"
          :placeholder="$t('routes.user.tiktok.channelPlaceholder')"
        >
          <template v-if="tiktokData.loading" #notFoundContent>
            <a-spin size="small" />
          </template>
        </a-select>
      </a-form-item>

      <a-form-item v-if="Number(form.status) === 520" :label="$t('routes.user.tiktok.producer')" name="producerId">
        <a-select
          v-model:value="form.producerId"
          :fieldNames="{ label: 'name', value: 'id' }"
          :not-found-content="tiktokData.loading ? undefined : null"
          :options="tiktokData.producerList"
          :placeholder="$t('routes.user.tiktok.producerPlaceholder')"
        >
          <template v-if="tiktokData.loading" #notFoundContent>
            <a-spin size="small" />
          </template>
        </a-select>
      </a-form-item>


      <a-form-item v-if="Number(form.status) === 521" :label="$t('routes.user.tiktok.tiktok')" name="ids">
        <a-select
          v-model:value="form.ids"
          :fieldNames="{ label: 'uniqueName', value: 'id' }"
          :not-found-content="tiktokData.loading ? undefined : null"
          :options="tiktokData.tiktokList"
          :placeholder="$t('routes.user.tiktok.tiktokPlaceholder')"
          mode="multiple"
          @select="handleOnChange"
        >
          <template v-if="tiktokData.loading" #notFoundContent>
            <a-spin size="small" />
          </template>
        </a-select>
      </a-form-item>

    </a-form>
  </a-modal>
</template>

<style lang="less" scoped>

</style>
